# Copyright 2022 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
import argparse
import os
import glob
import numpy as np

import sys
sys.path.append('..')
from sdk.main import SegmentationMetric

## Params
parser = argparse.ArgumentParser()
parser.add_argument('--label_path', type=str
                    , help='directory of dataset label')
parser.add_argument('--output_path', default=None, type=str
                    , help='path of the predict files that generated by the model')
parser.add_argument('--image_width', default=2048, type=int, help='image_width')
parser.add_argument('--image_height', default=1024, type=int, help='image_height')
args = parser.parse_args()


def cal_mIoU():
    file_list = glob.glob(os.path.join(args.label_path, '*'))
    metric = SegmentationMetric(19)
    metric.reset()
    for index, file in enumerate(sorted(file_list)):
        label = np.fromfile(file, dtype=np.int32)
        label = label.reshape(args.image_height, args.image_width)

        filename = file.split(os.sep)[-1][:-10]  # get the name of image file
        predict_path = os.path.join(args.output_path, filename + "_0.bin")
        predict = np.fromfile(predict_path, dtype=np.float32)
        predict = predict.reshape(1, 19, args.image_height, args.image_width)
        metric.update(predict, label)
        pixAcc, mIoU = metric.get()
        print("[EVAL] Sample: {:d}, pixAcc: {:.3f}, mIoU: {:.3f}".format(index + 1, pixAcc * 100, mIoU * 100))

    pixAcc, mIoU, category_iou = metric.get(return_category_iou=True)
    print('End validation pixAcc: {:.3f}, mIoU: {:.3f}'.format(pixAcc * 100, mIoU * 100))

if __name__ == '__main__':
    cal_mIoU()
